package com.example.rotateimageview.rotateImage

import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.util.SparseArray
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.DecelerateInterpolator
import android.view.animation.RotateAnimation
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.AppCompatImageView
import com.example.rotateimageview.R
import java.lang.IllegalStateException

/**
 * author  : Liushuai
 * time    : 2021/8/29 9:33
 * desc    :
 */
class RotateImage @JvmOverloads constructor(
    context:Context,
    attributeSet: AttributeSet?=null
) :AppCompatImageView(context,attributeSet) {

    private val arrayShowImage= SparseArray<RotateImageBean>()

    private var firstAnimation:Animation = RotateImageAnimation(0f,90f)
    private var secondAnimation:Animation = RotateImageAnimation(90f,180f)

    private var currentShowIndex=1
    private val MAX_SHOW_COUNT=2
    init {
        firstAnimation.fillAfter=true
        firstAnimation.duration=300
        firstAnimation.interpolator = AccelerateInterpolator()
        secondAnimation.fillAfter=true
        secondAnimation.duration=300
        secondAnimation.interpolator=DecelerateInterpolator()
    }

    override fun onDraw(canvas: Canvas?) {
        if (arrayShowImage[1] != null) {
           setImageResource(arrayShowImage[currentShowIndex].res)
        }
        super.onDraw(canvas)
    }

    fun startRotateAnimation() {
        firstAnimation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                currentShowIndex++
                if (currentShowIndex > MAX_SHOW_COUNT || arrayShowImage[currentShowIndex]== null) {
                    currentShowIndex=1
                }
                setImageResource(arrayShowImage[currentShowIndex].res)
                startAnimation(secondAnimation)
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })

        startAnimation(firstAnimation)
    }

    fun addShowView(showView:RotateImageBean) {
        if (arrayShowImage.get(showView.showPosition) == null) {
            arrayShowImage.put(showView.showPosition,showView)
        }else{
            throw IllegalStateException("position error")
        }
    }


    override fun setOnClickListener(l: OnClickListener?) {
        if (arrayShowImage.get(currentShowIndex) != null) {
            arrayShowImage.get(currentShowIndex).clickStatic?.invoke()
        }
    }

   data class RotateImageBean(@DrawableRes val res: Int,
                              val showPosition:Int,
                              val clickStatic:(()->Unit)?=null)
}